//
//  SERegistrationConfirmViewModel.swift
//  SmartEyeForPatient
//
//  Created by qdsg on 2021/7/26.
//

import UIKit
import YYText

enum SERegistrationConfirmCardType: Int {
    /// 正常选择卡片
    case selected
    /// 有卡片需要验证手机号
    case auth
    /// 无卡片需要建档
    case uncreate
    /// 不需要建档直接挂号
    case unselected
}

class SERegistrationConfirmViewModel: SEBaseViewModel {

    var authViewModel = SEAuthViewModel()
    var msgCodeHandler: ((SEHttpStatus) -> Void)?
    var checkCodeHandler: ((SEHttpStatus) -> Void)?
    var createCardHandler: ((SEHttpStatus) -> Void)?

    var isAgree = false
    var numItem = SERegistrationNumItem()
    var hospitalId = ""
    var hospitalName = ""
    var msgCode = ""
    var needBindCard = false
    var doctorShift = SERegistrationDoctorShift()
    var patientListItem = SEPatientDetailViewModel()
    var patientListCellModel: SERegistrationConfirmPatientCellModel {
        return SERegistrationConfirmPatientCellModel(titleText: "选择就诊人",
                                                     memoPlaceHolder: "请选择",
                                                     memoText: patientListItem.model.name,
                                                     isHiddenArrow: false)
    }

    var sourceId: String = ""

    var cardPhoneStr: String {
        if let cardPhone = patientListItem.model.cardPhone, cardPhone.count > 4 {
            let subStr = cardPhone.subString(index: 3, length: 4)
            return cardPhone.replacingOccurrences(of: subStr, with: "****")
        }
        return ""
    }

    var selectedCardModel: CardModel?

    struct CardModel {
        /// 1 自费卡 2 社保卡
        var cardType: Int = 0
        /// 卡片名称
        var cardName: String = ""
        /// 卡片号码
        var cardNum: String = ""
    }

    var cardModels: [CardModel] {
        var models: [CardModel] = []
        if let socialNum = patientListItem.model.patientCardPo?.socialSecurityNum, !socialNum.isEmpty {
            models.append(CardModel(cardType: 2, cardName: "社保卡", cardNum: socialNum))
        }
        if let ownNum = patientListItem.model.patientCardPo?.ownExpenseNum, !ownNum.isEmpty {
            models.append(CardModel(cardType: 1, cardName: "自费卡", cardNum: ownNum))
        }
        if let model = models.first, selectedCardModel == nil {
            selectedCardModel = model
        }
        return models
    }

    var cardListCellModels: [SERegistrationCardListCellModel] {
        return cardModels.map {
            SERegistrationCardListCellModel(title: $0.cardName, isSelected: $0.cardNum == selectedCardModel?.cardNum)
        }
    }

    func cardListCellModel(index: Int) -> SERegistrationCardListCellModel {
        cardListCellModels[index]
    }

    var cardType: SERegistrationConfirmCardType {
        SERegistrationConfirmCardType(rawValue: patientListItem.model.operationType ?? 3) ?? .unselected
    }

    var cardMemoStr: NSMutableAttributedString {
        let att = [NSAttributedString.Key.foregroundColor: UIColor(hex: "666666")]
        switch cardType {
        case .selected:
            let string = "查到您在\(hospitalName)存在\(cardModels.count)张就诊卡，请选择一张就诊卡预约"
            let range1 = string.range(of: hospitalName)
            let range2 = string.range(of: "\(cardModels.count)")
            let attStr = NSMutableAttributedString(string: string)
            guard range1 != nil, range2 != nil else {
                return attStr
            }
            attStr.addAttributes(att, range: NSRange(range1!, in: string))
            attStr.addAttributes(att, range: NSRange(range2!, in: string))
            return attStr
        case .auth:
            let string = "查到您在\(hospitalName)存在\(cardModels.count)张就诊卡，但院内预留手机号与当前预约手机号不一致，请按以下提示选择就诊卡并验证身份预约"
            let range1 = string.range(of: hospitalName)
            let range2 = string.range(of: "\(cardModels.count)")
            let attStr = NSMutableAttributedString(string: string)
            guard range1 != nil, range2 != nil else {
                return attStr
            }
            attStr.addAttributes(att, range: NSRange(range1!, in: string))
            attStr.addAttributes(att, range: NSRange(range2!, in: string))
            return attStr
        default:
            return NSMutableAttributedString()
        }
    }

    var msgTipStr: String {
        return "向院内预留手机号\(cardPhoneStr)发送验证码"
    }

    var cardCreateStr: NSAttributedString {
        let string = "查询到您在\(hospitalName)没有就诊卡，系统将按照手机号\(patientListItem.model.phone)为您建卡并预约(目前在线建档仅支持创建自费卡档案)"
        let att = [NSAttributedString.Key.foregroundColor: UIColor(hex: "666666")]
        let range = string.range(of: hospitalName)
        let attStr = NSMutableAttributedString(string: string)
        guard range != nil else {
            return attStr
        }
        attStr.addAttributes(att, range: NSRange(range!, in: string))
        return attStr
    }

    // MARK: - UI

    var cardMemoStrHeight: CGFloat {
        let layout = YYTextLayout(containerSize: CGSize(width: UIScreen.screenWidth - 30, height: CGFloat.greatestFiniteMagnitude), text: cardMemoStr)
        return layout?.textBoundingSize.height ?? 0
    }

    var numberOfSections: Int {
        return 5
    }

    func numberOfRowsInSection(section: Int) -> Int {
        switch section {
        case 0, 1: return 1
        case 2: return (cardType == .selected || cardType == .auth) ? cardListCellModels.count : 0
        case 3: return cardType == .auth ? 2 : 0
        case 4: return cardType == .uncreate ? 1 : 0
        default: return 0
        }
    }

    func heightForRowAt(indexPath: IndexPath) -> CGFloat {
        switch indexPath.section {
        case 0: return 172
        case 1, 2, 3: return 40
        case 4: return UITableView.automaticDimension
        default: return 0
        }
    }

    func heightForHeaderInSection(section: Int) -> CGFloat {
        switch section {
        case 0: return 0
        case 1: return 10
        case 2: return cardType != .uncreate ? (cardMemoStrHeight + 20) : 0
        case 3: return 0
        case 4: return cardType == .uncreate ? 10 : 0
        default: return 0
        }
    }

    var checkSubmit: String? {
        if patientListItem.model.id.isEmpty {
            return "请选择就诊人"
        }
        if needBindCard && selectedCardModel == nil {
            return "请选择就诊卡"
        }
        if cardType == .auth && msgCode.isEmpty {
            return "请输入验证码"
        }
        if !isAgree{
            return "请阅读并同意挂号须知"
        }
        return nil
    }

    // MARK: - APIRequest

    @objc func requestNumSubmit() {

        if let msg = checkSubmit {
            SEHUD.showError(message: msg)
            return
        }

        SEHttpManager.shared.requestForAny(SERegistrationAPI.registrationSubmit(sourceId: numItem.id, patientId: patientListItem.model.id, cardType: selectedCardModel?.cardType, cardNum: selectedCardModel?.cardNum), withLoading: true) { (result, status) in
            switch status {
            case .success: self.sourceId = result as? String ?? self.sourceId
            default: break
            }
            self.updateData?(status)
        }
    }

    /// 获取验证码
    func requestMsgCode() {
        authViewModel.account = patientListItem.model.cardPhone ?? ""
        authViewModel.requestMsgCode()
        authViewModel.msgCodeHandler = msgCodeHandler
    }

    /// 校验验证码
    func requestCheckMsgCode() {
        if let msg = checkSubmit {
            SEHUD.showError(message: msg)
            return
        }
        SEHttpManager.shared.requestForAny(SERegistrationAPI.checkMsg(code: msgCode, phone: patientListItem.model.cardPhone ?? "", patientId: patientListItem.model.id, hospitalId: hospitalId), withLoading: true) { result, status in
            switch status {
            case .success:
                self.perform(#selector(self.requestNumSubmit), with: nil, afterDelay: 0.25)
            default:
                break
            }
            self.checkCodeHandler?(status)
        }
    }

    /// 创建档案
    func requestCreateCard() {
        SEHttpManager.shared.request(SEProfileAPI.patientCreateCard(phoneNo: patientListItem.model.phone, idCard: patientListItem.model.idNumber, name: patientListItem.model.name, provinceCode: patientListItem.model.province, cityCode: patientListItem.model.city, address: patientListItem.model.addr, hospitalId: hospitalId, patientId: patientListItem.model.id), model: SEPatientCreateCardModel.self, withLoading: true) { model, status in
            switch status {
            case .success:
                self.patientListItem.model.patientCardPo = SEPatientCardDetailModel()
                self.patientListItem.model.patientCardPo?.ownExpenseNum = model?.patientKey ?? ""
                self.patientListItem.model.operationType = 0
            default:
                break
            }
            self.createCardHandler?(status)
        }
    }

}
